<template>
	<view class="edit-specs">
		<swiper :disable-touch="false" :current="tabCurrentIndex" class="swiper-box" duration="300">
			<swiper-item class="tab-content" catchtouchmove="stopTouchMove">
				<scroll-view scroll-y="true" class="wrapper">
					<div class="specs-wrapper">
						<div v-for="(specsItem,indexItem) in specs">
							<div class="specs-item">
								<div class="text">规格名：</div>
								<u-input class="input" v-model="specsItem.name" type="text" placeholder="请输入规格名" />
								<div class="del" @click="specs.splice(indexItem,1)">
									<u-icon name="close-circle" color="#999999" size="32"></u-icon>
								</div>
							</div>
							<div class="specs-option">
								<div class="specs-item" v-for="(specsOption,indexOption) in specsItem.children">
									<div class="text">规格值：</div>
									<u-input class="input" v-model="specsOption.name" type="text"
										placeholder="请输入规格值" />
									<div class="del" @click="specs[indexItem].children.splice(indexOption,1)">
										<u-icon name="close-circle" color="#999999" size="32"></u-icon>
									</div>
								</div>
								<button class="button-add-option" @click="addSpescOption(indexItem)">添加规格值</button>
							</div>
						</div>
					</div>
					<button class="button-add" @click="addSpesc">添加规格</button>
				</scroll-view>
				<button class="button-add-next" @click="next">下一步</button>
			</swiper-item>
			<swiper-item class="tab-content" catchtouchmove="stopTouchMove">
				<scroll-view scroll-y="true" class="wrapper2">
					<div class="sku-list">
						<div class="sku-item" v-for="(item,index) in skuList">
							<div class="left">
								<div class="head">
									<span class="text" v-for="spec in item[0]">{{spec.title}}:{{spec.value}}</span>
								</div>
								<div class="body">
									<span class="text" :class="{'error':spec.error}" v-for="spec in item[1]">
										<span v-if="spec.slot==='images'">{{spec.title}} :
											{{spec.value?'[图片]':'--'}}</span>
										<span v-else>{{spec.title}} : {{spec.value||'--'}}</span>
									</span>
								</div>
							</div>
							<div class="right" @click="editSpecOption(index)">
								<u-icon name="edit-pen" color="#999999" size="32"></u-icon>
								<span>编辑</span>
							</div>
						</div>
					</div>
				</scroll-view>
				<div class="buttons-wrapper">
					<button class="button-add-prev" @click="prev">上一步</button>
					<button class="button-add-save" @click="saveSpec">保存规格</button>
				</div>
			</swiper-item>
			<swiper-item class="tab-content" catchtouchmove="stopTouchMove">
				<scroll-view scroll-y="true" class="wrapper2">
					<div class="edit-Spec-option">
						<div class="body-edit">
							<div class="item" v-for="item in editCurrentData[0]">
								<span class="text">{{item.title}}:</span>
								<span class="text">{{item.value}}</span>
							</div>
						</div>
						<div class="body-edit">
							<div class="item" v-for="(item,index) in editCurrentData[1]">
								<span class="text">{{item.title}}:</span>
								<div v-if="item.slot==='images'">
									<image v-if="item.value" class="add-image" @click="addImage(index)"
										:src="item.value" mode="aspectFill"></image>
									<div v-else class="add-image" @click="addImage(index)">
										<u-icon name="plus" soze="#666666" size="48"></u-icon>
										<span class="pho">图片</span>
									</div>
								</div>
								<u-input class="input" @input="specsInput" :disabled="item.disabled" v-else
									type="number" :placeholder="item.placeholder" v-model="item.value">
								</u-input>
							</div>
						</div>
					</div>
				</scroll-view>
				<button class="button-add-next" @click="confirmEditSpec">确定</button>
			</swiper-item>
		</swiper>
	</view>
</template>

<script>
	import api from "@/config/api.js";
	import storage from "@/utils/storage.js";
	import BigNumber from 'bignumber.js'
	let SpecOptionTimer = null
	export default {
		name: 'edit-specs',
		data() {
			return {
				editCurrentIndex: '',
				editCurrentData: [],
				tabCurrentIndex: 0,
				specs: [],
				skuList: []
			}
		},
		onLoad() {
			let goodsAll = uni.getStorageSync('GoodsAll')
			let goodsDetail = uni.getStorageSync('GoodsDetail')
			this.goodsType = goodsAll.goodsType
			let SpecsListDetail = uni.getStorageSync('SpecsListDetail')
			let SpecsListOption = uni.getStorageSync('SpecsListOption')
			if (SpecsListDetail) {
				this.skuList = SpecsListDetail
				this.tabCurrentIndex = 1
			}
			if (SpecsListOption.length !== 0) {
				this.specs = SpecsListOption
			}

		},
		methods: {
			// 禁止手动触发华东
			stopTouchMove() {
				return false;
			},
			next() {
				if (this.specs.length === 0) {
					uni.showToast({
						title: "请添加规格",
						icon: "none"
					})
					return false
				}
				for (let i = 0; i < this.specs.length; i++) {
					if (!this.specs[i].name) {
						uni.showToast({
							title: "规格名不能为空",
							icon: "none"
						})
						return false
					}
					if (this.specs[i].children.length === 0) {
						uni.showToast({
							title: "请给【" + this.specs[i].name + "】添加规格箱",
							icon: "none"
						})
						return false
					}
					for (let j = 0; j < this.specs[i].children.length; j++) {
						if (!this.specs[i].children[j].name) {
							uni.showToast({
								title: "规格值不能为空",
								icon: "none"
							})
							return false
						}

					}
				}
				this.skuTableColumn = [];
				this.skuTableData = [];
				let pushData = [];
				if (this.goodsType != "VIRTUAL_GOODS") {
					pushData.push({
						title: "重量",
						slot: "weight",
						value: '',
						placeholder: '请输入重量',
						error: false
					})
				}
				pushData.push({
					title: "货号",
					slot: "sn",
					value: '',
					placeholder: '请输入货号',
					error: false
				}, {
					title: "库存",
					slot: "quantity",
					value: '',
					placeholder: '请输入库存',
					error: false
				}, {
					title: "结算价(人民币)",
					slot: "cost",
					value: '',
					placeholder: '请输入结算价(人民币)',
					error: false
				}, {
					title: "零售价(焕贝)",
					slot: "price",
					value: '',
					placeholder: '请输入零售价(焕贝)',
					error: false
				}, {
					title: "提现率",
					slot: "fee",
					value: '',
					placeholder: '提现折扣率=现金结算价÷ 焕贝零售价',
					error: false,
					disabled: true
				}, {
					title: "图片",
					slot: "images",
					value: '',
					error: false
				});
				//克隆所有渲染的数据
				let cloneTemp = this.cloneObj(this.specs);
				//判定 是否存在规格分组
				//存放最终结果
				let result = [];
				//循环选中的 sku 数据
				cloneTemp[0].children.forEach((specItem) => {
					result.push({
						[cloneTemp[0].name]: specItem.name
					});
				});
				cloneTemp.splice(0, 1);
				result = this.specIterator(result, cloneTemp);
				console.log(result)
				result = result.map((item) => {
					let arr = []
					for (let i = 0; i < this.specs.length; i++) {
						let obj = {}
						obj[this.specs[i].name] = item[this.specs[i].name],
							obj.slot = this.specs[i].name
						obj.value = item[this.specs[i].name]
						obj.title = this.specs[i].name
						arr.push(obj)
					}
					return [arr, JSON.parse(JSON.stringify(pushData)), false]
				})
				console.log(result)
				this.skuList = result
				uni.setStorageSync('SpecsListOption', this.specs)
				this.tabCurrentIndex = 1
			},
			prev() {
				let that = this
				uni.showModal({
					content: '离开此页面数据将不会保存',
					confirmText: '上一步',
					success(res) {
						if (res.confirm) {
							that.tabCurrentIndex = 0
							uni.removeStorageSync('SpecsListDetail')
							console.log('用户点击确定');
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				})
			},
			saveSpec() {
				for (let j = 0; j < this.skuList.length; j++) {
					for (let i = 0; i < this.skuList[j][1].length; i++) {
						if (!this.skuList[j][1][i].value && this.skuList[j][1][i].slot !== 'images') {
							this.skuList[j][1][i].error = true
							uni.showToast({
								title: "规格值不能为空，请先编辑",
								icon: "none"
							})
							return
						}
						this.skuList[j][1][i].error = false
					}
				}
				uni.setStorageSync('SpecsListDetail', JSON.parse(JSON.stringify(this.skuList)))
				uni.setStorageSync('SpecsListOption', JSON.parse(JSON.stringify(this.specs)))

				uni.navigateBack()
			},
			addSpesc() {
				console.log(this.specs)
				this.specs.push({
					name: '',
					children: []
				})
			},
			addSpescOption(indexItem) {
				this.specs[indexItem].children.push({
					name: '',
				})
			},
			// 编辑规格箱
			editSpecOption(index) {
				this.tabCurrentIndex = 2
				this.editCurrentIndex = index
				this.editCurrentData = JSON.parse(JSON.stringify(this.skuList[index]))
			},
			// 监听编辑规格项
			specsInput(e) {
				clearTimeout(SpecOptionTimer)
				SpecOptionTimer = setTimeout(() => {
					let filter = this.editCurrentData[1].filter((item) => {
						return item.slot === 'price' || item.slot === 'cost'
					})
					for (let i = 0; i < filter.length; i++) {
						if (!filter[i].value) {
							this.editCurrentData[1][this.editCurrentData[1].length - 2].value = ''
							return false
						} else {
							if (
								!/^[+]{0,1}(\d+)$|^[+]{0,1}(\d+\.\d+)$/.test(filter[i].value) ||
								parseInt(filter[i].value) < 0 ||
								parseInt(filter[i].value) > 99999999
							) {
								this.editCurrentData[1][this.editCurrentData[1].length - 2].value = ''
								return false;
							}
						}
					}
					let costPrice = this.editCurrentData[1][this.editCurrentData[1].length - 4].value
					let pricePrice = this.editCurrentData[1][this.editCurrentData[1].length - 3].value
					this.editCurrentData[1][this.editCurrentData[1].length - 2].value = new BigNumber(costPrice)
						.div(pricePrice).dp(2, BigNumber.ROUND_DOWN).toNumber()
				}, 1000)
			},
			// 确定编辑
			confirmEditSpec() {
				for (let i = 0; i < this.editCurrentData[1].length; i++) {
					if (!this.editCurrentData[1][i].value) {
						let title = ''
						if (this.editCurrentData[1][i].slot === 'images') {} else {
							title += this.editCurrentData[1][i].title
							uni.showToast({
								title: title,
								icon: "none"
							})
							return
						}

					} else {
						if (this.editCurrentData[1][i].slot === 'images') {} else {
							if (
								!/^[+]{0,1}(\d+)$|^[+]{0,1}(\d+\.\d+)$/.test(this.editCurrentData[1][i].value) ||
								parseInt(this.editCurrentData[1][i].value) < 0 ||
								parseInt(this.editCurrentData[1][i].value) > 99999999
							) {
								uni.showToast({
									title: this.editCurrentData[1][i].title + '： 取值范围是0~99999999',
									icon: "none"
								})
								return;
							}
						}
					}
				}
				let filter = this.editCurrentData[1].filter((item) => {
					return item.slot === 'price' || item.slot === 'cost'
				})
				let costPrice = this.editCurrentData[1][this.editCurrentData[1].length - 4].value
				let pricePrice = this.editCurrentData[1][this.editCurrentData[1].length - 3].value
				let fee = new BigNumber(costPrice).div(pricePrice).dp(2, BigNumber.ROUND_DOWN).toNumber()
				this.editCurrentData[1][this.editCurrentData[1].length - 2].value = fee
				if (!(0 < fee && fee <= 1)) {
					uni.showToast({
						title: '商品规格项的结算价不能大于零售价!',
						icon: "none"
					})
					return
				}
				this.tabCurrentIndex = 1
				this.skuList[this.editCurrentIndex][1] = this.editCurrentData[1]
				console.log(this.skuList)
			},
			// 给规格添加图片
			addImage(index) {
				let Token = storage.getAccessToken()
				let that = this
				uni.chooseImage({
					count: 1,
					sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
					success: function(res) {
						var tempFilePaths = res.tempFilePaths
						for (let i = 0; i < tempFilePaths.length; i++) {
							uni.uploadFile({
								url: api.common + '/upload/file',
								fileType: "image",
								filePath: tempFilePaths[i],
								name: 'file',
								ruleForm: {},
								'content-type': 'multipart/form-data',
								header: {
									accessToken: Token,
									'content-type': 'multipart/form-data'
								}, // 设置请求的 header
								success: function(res) {
									res = JSON.parse(res.data)
									that.editCurrentData[1][index].value = res.result
								}
							})
						}

					}
				})
			},
			/**
			 * 迭代属性，形成表格
			 * result 渲染的数据
			 * array spec数据
			 */
			specIterator(result, cloneTemp) {
				//是否还可以循环
				if (cloneTemp.length > 0) {
					let table = [];
					result.forEach((resItem) => {
						cloneTemp[0].children.forEach((valItem) => {
							let obj = this.cloneObj(resItem);
							obj[cloneTemp[0].name] = valItem.name;

							table.push(obj);
						});
					});
					result = [];
					table.forEach((t) => {
						result.push(t);
					});
					//清除当前循环的分组
					cloneTemp.splice(0, 1);
				} else {
					return result;
				}
				return this.specIterator(result, cloneTemp);
			},
			cloneObj(obj) {
				let str = null
				let newobj = obj.constructor === Array ? [] : {}
				if (typeof obj !== 'object') {
					return
				} else {
					for (var i in obj) {
						newobj[i] = typeof obj[i] === 'object' ? this.cloneObj(obj[i]) : obj[i]
					}
				}
				return newobj
			},
		}
	}
</script>

<style lang="scss" scoped>
	.edit-specs {
		.swiper-box {
			width: 100vw;
			height: 100vh;
		}

		.wrapper {
			padding: 32upx;
			height: 86vh;
			overflow: auto;
		}

		.wrapper2 {
			height: 86vh;
			overflow: auto;

			.sku-list {
				.sku-item {
					background-color: #ffffff;
					padding: 24upx 32upx;
					margin: 24upx 0;
					display: flex;

					.left {
						flex: 1;
						padding: 0 24upx 0 0;
					}

					.right {
						flex: 0 0 120upx;
						display: flex;
						align-items: center;
						justify-content: space-around;
						color: #999999;
					}

					.head {
						display: flex;
						flex-wrap: wrap;

						.text {
							margin: 4upx 32upx 4upx 0;
							font-size: 30upx;
						}
					}



					.body {
						margin-top: 12upx;
						display: flex;
						flex-wrap: wrap;

						.text {
							margin: 4upx 32upx 4upx 0;
							font-size: 28upx;
							color: #B3B3B3;
						}

						.error {
							color: #ff5e61;
						}
					}
				}
			}
		}

		.specs-wrapper {
			min-height: 300upx;

			.specs-item {
				margin: 16upx 0;
				display: flex;
				align-items: center;

				.text {
					flex: 0 0 120upx;
				}

				.input {
					flex: 0 0 240upx;
					padding: 0 16upx;
					background-color: #ffffff;
					border-radius: 8upx;
				}

				.del {
					display: flex;
					align-items: center;
					justify-content: center;
					margin-left: 24upx;
					flex: 0 0 56upx;
					width: 56upx;
					height: 56upx;
				}
			}

			.specs-option {
				padding: 12upx 0 12upx 120upx;
			}
		}

		.edit-Spec-option {
			.body-edit {
				.item {
					padding: 24upx 48upx;
					display: flex;
					margin: 16upx 0;
					align-items: center;
					background-color: #ffffff;

					.text {
						white-space: nowrap;
						margin: upx 24upx upx 0;
						font-size: 30upx;
						padding-right: 32upx;
					}

					.input {
						flex: 1;
					}

					.add-image {
						width: 160upx;
						height: 160upx;
						border-radius: 12upx;
						background-color: #EBEBEB;
						display: flex;
						flex-direction: column;
						align-items: center;
						justify-content: center;

						.pho {
							margin-top: 24upx;
							font-size: 24upx;
							color: #666666;
						}
					}
				}
			}
		}

		.buttons-wrapper {
			display: flex;
			justify-content: space-around;

			.button-add-prev {
				margin-top: 32upx;
				width: 260upx;
				height: 80upx;
				line-height: 80upx;
				background: linear-gradient(270deg, rgba(118, 194, 245, 1) 0%, rgba(18, 125, 255, 1) 100%);
				border-radius: 40upx;
				color: #ffffff;
				font-size: 28upx;
			}

			.button-add-save {
				margin-top: 32upx;
				width: 260upx;
				height: 80upx;
				line-height: 80upx;
				background: linear-gradient(270deg, rgba(255, 98, 0, 1) 0%, rgba(240, 139, 67, 0.65) 100%);
				border-radius: 40upx;
				color: #ffffff;
				font-size: 28upx;
			}
		}

		.button-add-option {
			margin: 0;
			width: 180upx;
			height: 48upx;
			line-height: 48upx;
			background: linear-gradient(162.65deg, rgba(255, 98, 0, 1) 0%, rgba(240, 139, 67, 0.65) 100%);
			border-radius: 48upx;
			color: #ffffff;
			font-size: 24upx;
		}

		.button-add {
			margin-top: 32upx;
			width: 360upx;
			height: 64upx;
			line-height: 64upx;
			background: linear-gradient(270deg, rgba(118, 194, 245, 1) 0%, rgba(18, 125, 255, 1) 100%);
			border-radius: 40upx;
			color: #ffffff;
			font-size: 28upx;
		}

		.button-add-next {
			margin-top: 32upx;
			width: 560upx;
			height: 80upx;
			line-height: 80upx;
			background: linear-gradient(270deg, rgba(118, 194, 245, 1) 0%, rgba(18, 125, 255, 1) 100%);
			border-radius: 40upx;
			color: #ffffff;
			font-size: 28upx;
		}
	}
</style>
